#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "ai.h"


int main()
{
    mode = MODE_AUTO;
    int i;
    
    while(1)
    {
    	main_loop();
    }
    getch();
    return 0;
}

int main_loop ( void )
{
    while( mode == MODE_AUTO )
    {
	/*send a request for planes list */
	send(/*servPID, msgbuff, replybuff, sizeof(msgbuff), sizeoff(replybuff)*/);
	
	assign_pri();
	sort( first_plane );
	if( ( no_planes[0] + no_planes[1] + no_planes[2] ) >= ( 2 * no_strips + hangar_vol ) )
		reroute_planes();
    }
    return 0;
}

void assign_pri ( void )
{
    PLANE_DATA * temp;
    temp = first_plane;
    do
    {
        if( temp->state == PLANE_WAITING_TO_LAND )
	{
	    if( temp->emergency == TRUE )
		temp->priority = -1;
	    else
		temp->priority = temp->fuel * ( temp->distance + 1 );
	}
	temp = temp->next;
    } while( temp != NULL );
    
}

void sort ( PLANE_DATA * first )
{
    PLANE_DATA * temp;
    PLANE_DATA * tmp1;
    PLANE_DATA * tmp2;
    PLANE_DATA * newlist;
    
    newlist = first;
    temp = first->next;
    tmp1 = newlist;
    newlist->next = NULL;
    while ( temp != NULL )
    {
	tmp1 = newlist;
	while ( ( tmp1->priority < temp->priority ) && ( tmp1-> next != NULL ) )
	{	
	    tmp1 = tmp1->next;
	}
	
	/* insert the element */
	if ( temp == tmp1 )
	{
	    /* do nothing */
	}
	else if ( ( tmp1->next == NULL ) && ( tmp1->priority < temp->priority ) )
	{
	    /* insert after */
	    tmp2 = temp;
	    if ( temp->prev != NULL )
		temp->prev->next = temp->next;
	    if ( temp->next != NULL )
		temp->next->prev = temp->prev;
	    temp = temp->next;
	    tmp2->next = tmp1->next;
	    tmp2->prev = tmp1;
	    tmp1->next = temp;
	}
	else
	{
	    /* insert before */
	    tmp2 = temp;
	    if ( temp->prev != NULL )
		temp->prev->next = temp->next;
	    if ( temp->next != NULL )
		temp->next->prev = temp->prev;
	    temp = temp->next;
	    tmp2->next = tmp1;
	    tmp2->prev = tmp1->prev;
	    tmp1->prev = temp;
	}
    }
    first = newlist;
    
}

void reroute_planes (void)
{
    temp = first_plane;
    int i;
    for( i = 0; i < ( 2 * no_strips + hangar_vol ); i++ )
    {
	temp = temp->next;
    }
    while( temp != NULL )
    {
	tmep->reroute = TRUE;
    }
}
